<?php

class LocationsController extends BaseController
{
    /**
     * Location model
     * @var Location
     */
    protected $location;

    /**
     * Inject the models.
     *
     * @param Location $location is model Location
     */
    public function __construct(Location $location)
    {
        parent::__construct();
        $this->location = $location;
    }

    public function getIndex()
    {

       $provinces = Province::all();
       $defaulProvince = $this->getProvinceBySlug($provinces, 'phnom-penh');
       $branches = ProvincePlaces::getBranches($defaulProvince->id);

       $atms = Location::whereIn('branch_id', $this->branchArrayId($branches))
                        ->get()
                        ->toJson();

        // Show the page
        return View::make('site/locations/index', compact('provinces', 'defaulProvince', 'branches', 'atms'));

    }

    public function getBankByProvince($province_id)
    {
        //ProvincePlaces bank or branch
        $branches = ProvincePlaces::getBranches($province_id);
        $province = Province::find($province_id)->toArray();
        //ATM by province
        $atms = Location::whereIn('branch_id', $this->branchArrayId($branches))
                        ->get()
                        ->toArray();

        $data = array('atms' => $atms, 'branches' => $branches->toArray(), 'province' => $province);

        return Response::json($data);
    }

    private function getProvinceBySlug($provinces, $slug)
    {
        $tmp = '';
        foreach ($provinces as $p) {
            if ($p->slug === $slug) {
                $tmp = $p;
                break;
            }
        }

        return $tmp;
    }

    private function branchArrayId($branches)
    {
        $tmp = array();
        foreach ($branches as $b) {
            $tmp[] = $b->id;
        }

        return $tmp;
    }
}
